package com.example.screenprojection;

import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;


import org.greenrobot.eventbus.EventBus;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Objects;


public class UDPBroadcastService extends Service {
    private static final int BROADCAST_PORT = 50001;  // 广播端口
    private static final int BROADCAST_PORT2 = 50005;  // 广播端口
    private static final String BROADCAST_ADDRESS = "255.255.255.255";  // 广播地址
    private static final String TAG = "UDPBroadcastService";
    private boolean isBroadcasting = false;  // 用于标记是否正在广播
    private String lastReceivedMessage = ""; // 用于保存上一个接收到的消息

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "UDPBroadcastService 创建");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!isBroadcasting) {
            // 启动广播线程
            startBroadcast();
            startListening();

        }
        return START_STICKY;  // 服务重新启动时继续运行
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopBroadcast();
        Log.d(TAG, "UDPBroadcastService 销毁");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;  // 不绑定到 UI
    }


    private void startBroadcast() {
        new Thread(() -> {
            try (DatagramSocket socket = new DatagramSocket()) {
                socket.setBroadcast(true);  // 启用广播模式

                String deviceModel = Build.MODEL;  // 获取设备型号
                String message = " Model:" + deviceModel;
                byte[] buffer = message.getBytes();

                InetAddress broadcastAddress = InetAddress.getByName(BROADCAST_ADDRESS);
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length, broadcastAddress, BROADCAST_PORT);

                isBroadcasting = true;
                while (isBroadcasting) {
                    socket.send(packet);  // 发送广播
//                                Log.d(TAG, "广播已发送: " + message);
                    try {
                        Thread.sleep(1000);  // 每秒广播一次
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "广播发送时出错: ", e);
            }
        }).start();
    }

    private void stopBroadcast() {
        isBroadcasting = false;  // 停止广播
    }

    private void startListening() {
        new Thread(() -> {
            try (DatagramSocket socket = new DatagramSocket(BROADCAST_PORT2)) {
                socket.setBroadcast(true);  // 启用广播模式

                byte[] buffer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

                // 接收来自服务端的广播包
                while (true) {
                    socket.receive(packet);
                    String receivedMessage = new String(packet.getData(), 0, packet.getLength());
                    InetAddress senderAddress = packet.getAddress();
                    String serverIp = senderAddress.getHostAddress();
                    Log.d(TAG, "接收到广播: " + receivedMessage + serverIp);
                    // 判断接收到的消息是否与上次接收到的相同
                    NetworkUtils NetWorkUtil = null;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (!receivedMessage.equals(lastReceivedMessage) && !Objects.equals(serverIp, NetWorkUtil.getLocalIpAddress(this))) {
                            lastReceivedMessage = receivedMessage; // 更新上次接收到的消息
                            EventBus.getDefault().post(new ScreeDevices(receivedMessage)); // 发送消息
                        } else {
                            Log.d(TAG, "接收到重复的广播信息，不发送");
                        }
                    }
                    // 可以根据需求将信息发送给其他组件（如通过广播或启动 Activity 等）
                }
            } catch (Exception e) {
                Log.e(TAG, "接收广播时出错: ", e);
            }
        }).start();
    }




}
